package com.ruoyi.web.controller.system;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.config.YfGlobal;
import com.ruoyi.common.exception.file.InvalidExtensionException;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.responseBodyJson.JSON;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.yf.domain.Report;
import com.ruoyi.yf.domain.YfDept;
import com.ruoyi.yf.service.IYfDeptService;
import com.ruoyi.yf.tool.GenerateDeptName;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.Null;


/**
 * 机构信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    private String prefix = "system/dept";
//    private static final Logger log = LoggerFactory.getLogger(SysDeptController.class);

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IYfDeptService yfDeptService;

    @Autowired
    private ISysConfigService configService;


    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;
    //查询本机构下所有未签约的医院
    @GetMapping("/selectHospitalAll")
    @ResponseBody
    @JSON(type = SysDept.class,include = "deptName")
    public AjaxResult selectHospitalAll(){
        //这里返回的数据中要有医院id
          return toAjaxFull(deptService.selectHospitalAll());
    }
    //根据处置公司id查询出所管理的医院信息
    //TODO 这个接口的权限控制还没加，后期记得加上
    @GetMapping("/hospitalAll")
    @ResponseBody
    @JSON(type = SysDept.class, include = "deptId,deptName,extName,deptType,status")
    public AjaxResult hospitalAll(){
        return toAjaxFull(deptService.selectHospitalInfo(ShiroUtils.getSysUser().getDeptId()));
    }
    //efd6bc3c-2d63-4822-8d84-a500d92b9122
    @RequiresPermissions("system:dept:view")
    @GetMapping()
    public String dept() {
        return prefix + "/dept";
    }

//    4abc1921-5370-44e5-a661-a1691bca7343
    @RequiresPermissions("system:dept:view")
    @GetMapping("/hospital")
    public String hospital() {
        return prefix + "/hospital";
    }
//426690c8-d28d-4f2f-83b3-57204f615661
    @RequiresPermissions("system:dept:list")
    @PostMapping("/list")
    @ResponseBody
//a6f99261-7261-42ec-989e-882282224486
    public List<SysDept> list(SysDept dept) {
//        if (dept.getParentId() == null ) {
//            dept.setAncestors(ShiroUtils.getSysUser().getDeptId().toString());
//            dept.setDeptId(ShiroUtils.getSysUser().getDeptId());
//        }
        System.out.println("=========="+dept);
        return deptService.selectDeptList(dept);
    }

    /**
     * 医院及医院以下机构列表
     *
     * @param dept
     * @return
     * dc24770f-f33b-428b-961c-dc4e30ca9f6d
     */
    @RequiresPermissions("system:dept:list")
    @PostMapping("/hospitallist")
    @ResponseBody
    public List<SysDept> hospitallist(SysDept dept) {
        List<SysDept> deptList = deptService.selectHospitalList(dept);
        return deptList;
    }


    /**
     * XiaoYi...
     * @param stagingId 暂存点 id
     * @Date : 2020-03-18 17:08
     * 6b60c15f-1ed6-4296-8099-1559602428c5
     */
//    @Log(title = "查询暂存点") //超出log内容长度
//    @RequiresPermissions("system:dept:list")
//    @PostMapping("/adds/list")
//    @ResponseBody
//    public TableDataInfo getDepList(String stagingId) {
//        List<SysDept> sysDepts = deptService.selectHospital(grade, hospitalId);
//        return getDataTable(sysDepts);
//    }

    /**
     * 新增机构
     * 1d23f4b6-ff8d-41a9-8f8f-be689e474a8b
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        if (parentId < 0)
            parentId = ShiroUtils.getSysUser().getDeptId();
        mmap.put("dept", deptService.selectDeptById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存机构
     * de7cf555-60c6-41e2-8ddd-6dd7c903c08a
     */
    @Log(title = "机构管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("system:dept:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysDept dept) {
        System.out.println("dept:" + dept);
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("新增机构'" + dept.getDeptName() + "'失败，机构名称已存在");
        }
        if (deptService.checkDeptExistUser(dept.getDeptId())) {
            return error("新增机构'" + dept.getDeptId() + "'失败，机构编号已被占用");
        }
        dept.setCreateBy(ShiroUtils.getLoginName());
        return toAjaxFull(deptService.insertDept(dept), dept.getDeptId());
    }

    //39709ec2-549f-4e76-886a-ce81a6f500c0
    @RequestMapping(value = "/uploadLogo", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult uploadLogo(@RequestParam("logo") MultipartFile file, @RequestParam("did") String did, @RequestParam("fileId") String fileId) {
        String upload = "";
        SysDept dept = new SysDept();
        dept.setDeptId(Long.valueOf(did));
        if (file != null) {
            try {
                upload = FileUploadUtils.upload(YfGlobal.Path.logo, file, did);
                dept.setLogo(upload);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InvalidExtensionException e) {
                e.printStackTrace();
            }
        }
        return toAjaxFull(deptService.updateDept(dept), dept.getLogo());
    }

    //dd5bab37-8356-4a9a-a69b-ab3338c9f580
    @RequestMapping(value = "/delLogo", method = RequestMethod.POST)
    @ResponseBody
    public AjaxResult delLogo(@RequestParam String did) {
        SysDept dept = new SysDept();
        dept.setDeptId(Long.valueOf(did));
        dept.setLogo("");
        return toAjaxFull(deptService.updateDept(dept), dept.getLogo());
    }

    /**
     * 修改
     * 49c0022f-f2c0-450c-8a5e-ea5729981d5e
     */
    @GetMapping("/edit/{deptId}")
    public String edit(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        SysDept dept = deptService.selectDeptById(deptId);
        if (StringUtils.isNotNull(dept) && 100L == deptId) {
            dept.setParentName("无");
        }
        mmap.put("dept", dept);
        return prefix + "/edit";
    }

    /**
     * 保存
     * f8949412-1cc4-4772-b151-8b2ce27542e8
     */
    @Log(title = "机构管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:dept:edit")
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysDept dept) {
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("修改机构'" + dept.getDeptName() + "'失败，机构名称已存在");
        } else if (dept.getParentId().equals(dept.getDeptId())) {
            return error("修改机构'" + dept.getDeptName() + "'失败，上级机构不能是自己");
        }

        dept.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(deptService.updateDept(dept));
    }


    /**
     * 删除
     * 0f89c5f1-f5eb-4f34-90dc-6b051175fba1
     */
    @Log(title = "机构管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("system:dept:remove")
    @GetMapping("/remove/{deptId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("deptId") Long deptId) {
        if (deptService.selectDeptCount(deptId) > 0) {
            return AjaxResult.warn("存在下级机构,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return AjaxResult.warn("机构存在用户,不允许删除");
        }
        if (deptService.selectYFCountByDeptId(deptId) > 0) {
            return AjaxResult.warn("机构存在医废,不允许删除");
        }
        if (deptService.selectKSCountByDeptId(deptId) > 0) {
            return AjaxResult.warn("机构存在科室,不允许删除");
        }
        return toAjax(deptService.deleteDeptById(deptId));
    }

    /**
     * 校验机构名称
     * 043f17d4-866b-48c7-8751-f8456e7f3aba
     */
    @PostMapping("/checkDeptNameUnique")
    @ResponseBody
    public String checkDeptNameUnique(SysDept dept) {
        return deptService.checkDeptNameUnique(dept);
    }

    /**
     * 选择机构树
     * 5c0c7101-34c8-46fd-b54f-2f8623ecc184
     */
    @GetMapping("/selectDeptTree/{deptId}")
    public String selectDeptTree(@PathVariable("deptId") Long deptId, ModelMap mmap) {
        if (deptId <= 0)
            deptId = ShiroUtils.getSysUser().getDeptId();
        mmap.put("dept", deptService.selectDeptById(deptId));
        return prefix + "/tree";
    }


    /**
     * 加载机构列表树
     * ddd159a9-cc04-417b-9df0-628efff2beb9
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData() {
        List<Ztree> ztrees = deptService.selectDeptTree(new SysDept());
        return ztrees;
    }

    /**
     * 加载角色机构（数据权限）列表树
     * 7d32b127-b6e9-4115-af5e-8ad7eebc8e62
     */
    @GetMapping("/roleDeptTreeData")
    @ResponseBody
    public List<Ztree> deptTreeData(SysRole role) {
        List<Ztree> ztrees = deptService.roleDeptTreeData(role);
        return ztrees;
    }


    /**
     * 科室转换为机构跳转
     *
     * @return
     * 8ec2ebd8-c175-467f-8345-6c5f75f6354e
     */
    @GetMapping("/toHospital/{parentId}")
    @RequiresPermissions("system:dept:edit")
    public String transitionHospital(@PathVariable("parentId") Long parentId, ModelMap mmap) {
        if (parentId > 0) {
            List<YfDept> yfDepts = yfDeptService.selectYfDeptListByDeptId(parentId, "20,30,40,50");
            mmap.put("department", yfDepts);
        }
        Long deptId = ShiroUtils.getSysUser().getDeptId();
//        返回当前角色下的机构
        SysDept dept = deptService.selectDeptById(deptId);
        mmap.put("dept", dept);
        System.out.println(dept);
        return prefix + "/transitionHospital";
    }

    //69b0f67a-5275-4d89-9a28-4d9a7488b40e
    @PostMapping("/transitionHospital")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult transitionHospital(@Validated SysDept dept) throws Exception {
        System.out.println("dept:" + dept);
        if (UserConstants.DEPT_NAME_NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return error("新增机构'" + dept.getDeptName() + "'失败，机构名称已存在");
        }
//        if (!StringUtils.isNotNull(dept.getDeptId() )|| deptService.checkDeptExistUser(dept.getDeptId())) {
//            return error("新增机构'" + dept.getDeptId() + "'失败，机构编号已被占用");
//        }
//          创建人登录名
        SysUser sysUser = ShiroUtils.getSysUser();

        dept.setCreateBy(sysUser.getLoginName());
        dept.setCreateId(sysUser.getUserId());

        //    是否创建暂存点
        //    是否创建暂存点用户

//        创建机构
        deptService.insertDept(dept);
        System.out.println("1.机构创建成功...");

//        创建暂存点
//      1.获取机构信息 并赋值
        SysDept zancundian = new SysDept();
//        名称
        zancundian.setDeptName("暂存点");
//        创人登录名
        zancundian.setCreateBy(sysUser.getLoginName());
//        父类集群
        zancundian.setAncestors(dept.getAncestors() + "," + dept.getDeptId());
//        父类id
        zancundian.setParentId(dept.getDeptId());
//        排序
        zancundian.setOrderNum("1");
//        等级
        zancundian.setHospitalGrade("0");
//        机构类型
        zancundian.setDeptType("400");
        deptService.insertDept(zancundian);
        System.out.println("2.暂存点创建成功...");

//        科室逻辑
        YfDept old_yfDept = new YfDept();

//        判断科室是否存在
        YfDept yfDept = yfDeptService.selectYfDeptById(dept.getDepartmentId());
        if (yfDept != null) {
            old_yfDept.setDeptId(dept.getDepartmentId());
        }
        //        判断 -- 创建科室并迁移科室

        old_yfDept.setUpdateBy(sysUser.getLoginName());
        old_yfDept.setCreateId(sysUser.getUserId());
//        科室迁移
        if (dept.getIsMedicalWasteTransferBoo().equals("1")) {
//            科室修改医院机构
            old_yfDept.setHospitalId(dept.getDeptId());
            //类型修改为科室
            old_yfDept.setType("10");
            yfDeptService.updateYfDept(old_yfDept);
            System.out.println("3.迁移科室完成...");
        }//新增
        else if (dept.getIsMedicalWasteTransferBoo().equals("2")) {
            if (yfDept != null) {
                //旧科室停用
                old_yfDept.setStatus("1");
                yfDeptService.updateYfDept(old_yfDept);
                System.out.println("旧科室暂停");
            }
//            新科室创建
            YfDept new_yfDept = new YfDept();
            new_yfDept.setDeptId(GenerateDeptName.deptName_15());
            new_yfDept.setHospitalId(dept.getDeptId());
            new_yfDept.setType("10");
            new_yfDept.setBuildingNo(1);
            new_yfDept.setDeptName("默认科室");
            new_yfDept.setCreateBy(sysUser.getLoginName());
            new_yfDept.setCreateId(sysUser.getUserId());
            yfDeptService.insertYfDept(new_yfDept);
            System.out.println("3.创建新科室完成...");
        }

//          判断是否创建医院管理员、填报员账号 密码默认
        if (dept.getIsCreateAdminUserBoo().equals("1")) {
//             创建账号 生成密码
            String password = configService.selectConfigByKey("sys.user.initPassword");
            String deptType = dept.getDeptType();
//            创建管理员
            Long[] type = null;
            if (deptType.equals("220")) {
                type = new Long[]{Long.valueOf(60)};
            } else if (deptType.equals("270")) {
                type = new Long[]{Long.valueOf(80)};
            } else if (deptType.equals("290") || deptType.equals("320")) {
                type = new Long[]{Long.valueOf(110)};
            }
            createUser(dept.getDeptLoginName(), password, dept.getDeptId(), 0, type);
//            创建填报员
            Long[] role = new Long[]{Long.valueOf(210)};
            createUser(dept.getDeptLoginName() + "002", password, zancundian.getDeptId(), 1, role);
            System.out.println("4.2创建用户完成...");
        }

        System.out.println("success");
        return successful();
    }

    //    添加角色
    //94d7821e-7fdd-4552-8d2a-980873abf3dc
    private int createUser(String loginName, String password, Long deptId, int type, Long[] roles) throws Exception {
        SysUser sysUser = ShiroUtils.getSysUser();

        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(loginName))) {
            throw new Exception("新增用户'" + loginName + "'失败，登录账号已存在");
//                return error("新增用户'" + new_user.getLoginName() + "'失败，登录账号已存在");
        }
        SysUser new_user = new SysUser();
        //    创建管理员
        if (type == 0) {
            new_user.setLoginType("200");
            new_user.setRoleIds(roles);
            new_user.setUserName("管理员");
            System.out.println("4.1开始创建管理员..." + Arrays.toString(roles));
        } else
            //    创建填报员
            if (type == 1) {
                new_user.setLoginType("300,400");
                new_user.setRoleIds(roles);
                new_user.setUserName("填报员");
                System.out.println("4.1开始创建填报员..." + Arrays.toString(roles));
            }
        new_user.setLoginName(loginName);
        new_user.setDeptId(deptId);
        new_user.setSalt(ShiroUtils.randomSalt());
        new_user.setPassword(passwordService.encryptPassword(new_user.getLoginName(), password, new_user.getSalt()));
        new_user.setCreateBy(sysUser.getLoginName());
        new_user.setCreateId(sysUser.getUserId());
        return userService.insertUser(new_user);
    }


}
